"""
订单服务
处理订单的创建、查询、更新等业务逻辑
"""

import uuid
from typing import List, Optional, Dict, Any
from datetime import datetime
from core.models.order import Order, OrderItem, OrderStatus
from core.services.data_manager import DataManager
from core.utils.logger import debug, info, warning, error
from core.utils.error_handler import handle_critical_errors, handle_warnings


class OrderService:
    """订单服务类"""
    
    def __init__(self):
        self.data_manager = DataManager()
    
    @handle_critical_errors("Failed to create order, please retry")
    def create_order(self, user_id: str, cart_items: List, 
                    shipping_address: str = None, auto_pay: bool = False) -> Order:
        """
        创建新订单
        
        Args:
            user_id: 用户ID
            cart_items: 购物车商品列表
            shipping_address: 收货地址
            auto_pay: 是否自动支付（True=已支付，False=待支付）
            
        Returns:
            Order: 创建的订单对象
        """
        # 生成订单ID
        order_id = f"ORD-{uuid.uuid4().hex[:8].upper()}"
        
        # 创建订单项列表
        order_items = []
        total = 0.0
        
        for cart_item in cart_items:
            # 从购物车项创建订单项
            product = cart_item.product
            order_item = OrderItem(
                product_id=product.product_id,
                product_name=product.name,
                price=product.price,
                quantity=cart_item.quantity,
                subtotal=cart_item.subtotal
            )
            order_items.append(order_item)
            total += order_item.subtotal
        
        # 创建订单对象
        order = Order(
            order_id=order_id,
            user_id=user_id,
            items=order_items,
            total=total,
            status=OrderStatus.PAID if auto_pay else OrderStatus.PENDING,  # 根据参数决定初始状态
            shipping_address=shipping_address
        )
        
        # 保存订单
        self._save_order(order)
        
        status_str = "Paid" if auto_pay else "Pending"
        info(f"✅ Order created successfully: {order_id}, user: {user_id}, total: ¥{total:.2f}, status: {status_str}")
        return order
    
    def _save_order(self, order: Order):
        """保存订单到数据文件"""
        orders_data = self.data_manager.load_data('orders.json') or []
        orders_data.append(order.to_dict())
        self.data_manager.save_data('orders.json', orders_data)
    
    def get_all_orders(self) -> List[Order]:
        """
        获取所有订单
        
        Returns:
            List[Order]: 订单列表
        """
        orders_data = self.data_manager.load_data('orders.json') or []
        orders = []
        
        for data in orders_data:
            try:
                order = Order.from_dict(data)
                orders.append(order)
            except Exception as e:
                error(f"Failed to parse order data: {e}")
                continue
        
        debug(f"📦 加载了 {len(orders)} 个订单")
        return orders
    
    def get_order_by_id(self, order_id: str) -> Optional[Order]:
        """
        根据订单ID获取订单
        
        Args:
            order_id: 订单ID
            
        Returns:
            Order: 订单对象，如果不存在返回None
        """
        orders = self.get_all_orders()
        for order in orders:
            if order.order_id == order_id:
                return order
        return None
    
    def get_user_orders(self, user_id: str) -> List[Order]:
        """
        获取指定用户的所有订单
        
        Args:
            user_id: 用户ID
            
        Returns:
            List[Order]: 用户的订单列表
        """
        all_orders = self.get_all_orders()
        user_orders = [order for order in all_orders if order.user_id == user_id]
        
        # 按创建时间倒序排列（最新的在前）
        user_orders.sort(key=lambda x: x.created_at, reverse=True)
        
        debug(f"👤 用户 {user_id} 有 {len(user_orders)} 个订单")
        return user_orders
    
    def update_order_status(self, order_id: str, new_status: OrderStatus) -> bool:
        """
        更新订单状态（带状态转换验证）
        
        Args:
            order_id: 订单ID
            new_status: 新状态
            
        Returns:
            bool: 是否更新成功
        """
        # 先获取订单对象进行验证
        order = self.get_order_by_id(order_id)
        if not order:
            warning(f"❌ Order {order_id} does not exist, cannot update status")
            return False
        
        # 验证状态转换是否合法
        if not order.can_transition_to(new_status):
            warning(f"❌ Order {order_id} in status {order.status} cannot transition to {new_status}")
            return False
        
        # 执行状态更新
        orders_data = self.data_manager.load_data('orders.json') or []
        
        for order_data in orders_data:
            if order_data.get('order_id') == order_id:
                # 更新状态和时间
                order_data['status'] = new_status.value
                order_data['updated_at'] = datetime.now().isoformat()
                
                # 保存更新
                self.data_manager.save_data('orders.json', orders_data)
                info(f"✅ Order {order_id} status updated to: {new_status.value}")
                return True
        
        warning(f"❌ Error occurred while updating order {order_id} status")
        return False
    
    @handle_critical_errors("Failed to cancel order, please retry")
    def cancel_order(self, order_id: str) -> bool:
        """
        取消订单并恢复库存
        
        Args:
            order_id: 订单ID
            
        Returns:
            bool: 是否取消成功
        """
        order = self.get_order_by_id(order_id)
        
        if not order:
            warning(f"❌ Order {order_id} does not exist")
            return False
        
        if not order.can_cancel():
            warning(f"❌ Order {order_id} in status {order.status} cannot be cancelled")
            return False
        
        # 恢复库存
        self._restore_order_stock(order)
        
        # 更新订单状态为已取消
        return self.update_order_status(order_id, OrderStatus.CANCELLED)
    
    def _restore_order_stock(self, order: Order) -> None:
        """
        恢复订单中商品的库存
        
        Args:
            order: 订单对象
        """
        try:
            from core.services.product_service import ProductService
            product_service = ProductService()
            
            restored_items = []
            failed_items = []
            
            for item in order.items:
                try:
                    # 增加商品库存
                    success = product_service.update_stock(item.product_id, item.quantity)
                    if success:
                        restored_items.append(f"{item.product_name} x{item.quantity}")
                        info(f"✅ Stock restored successfully: {item.product_name} +{item.quantity}")
                    else:
                        failed_items.append(f"{item.product_name} x{item.quantity} (product does not exist)")
                        warning(f"❌ Failed to restore stock: {item.product_name} - product does not exist")
                except Exception as e:
                    failed_items.append(f"{item.product_name} x{item.quantity} (error: {str(e)})")
                    error(f"❌ Exception while restoring stock: {item.product_name} - {e}")
            
            # 记录恢复结果
            if restored_items:
                info(f"📦 Order {order.order_id} stock restored successfully: {', '.join(restored_items)}")
            if failed_items:
                warning(f"⚠️ Order {order.order_id} partial stock restoration failed: {', '.join(failed_items)}")
                
        except Exception as e:
            error(f"❌ Exception occurred while restoring order {order.order_id} stock: {e}")
    
    def get_orders_by_status(self, status: OrderStatus) -> List[Order]:
        """
        获取指定状态的所有订单
        
        Args:
            status: 订单状态
            
        Returns:
            List[Order]: 订单列表
        """
        all_orders = self.get_all_orders()
        return [order for order in all_orders if order.status == status]
    
    def get_user_orders_by_status(self, user_id: str, status: OrderStatus) -> List[Order]:
        """
        获取用户指定状态的订单
        
        Args:
            user_id: 用户ID
            status: 订单状态
            
        Returns:
            List[Order]: 订单列表
        """
        user_orders = self.get_user_orders(user_id)
        return [order for order in user_orders if order.status == status]
    
    def get_order_statistics(self, user_id: str = None) -> Dict[str, Any]:
        """
        获取订单统计信息
        
        Args:
            user_id: 用户ID（可选，如果提供则只统计该用户的订单）
            
        Returns:
            Dict: 统计信息
        """
        if user_id:
            orders = self.get_user_orders(user_id)
        else:
            orders = self.get_all_orders()
        
        stats = {
            'total_orders': len(orders),
            'total_amount': sum(order.total for order in orders),
            'pending_orders': len([o for o in orders if o.status == OrderStatus.PENDING]),
            'paid_orders': len([o for o in orders if o.status == OrderStatus.PAID]),
            'shipped_orders': len([o for o in orders if o.status == OrderStatus.SHIPPED]),
            'completed_orders': len([o for o in orders if o.status == OrderStatus.COMPLETED]),
            'cancelled_orders': len([o for o in orders if o.status == OrderStatus.CANCELLED])
        }
        
        return stats
    
    def has_user_purchased_product(self, user_id: str, product_id: str) -> bool:
        """
        检查用户是否购买过指定商品
        
        Args:
            user_id: 用户ID
            product_id: 商品ID
            
        Returns:
            bool: 是否购买过
        """
        user_orders = self.get_user_orders(user_id)
        
        for order in user_orders:
            # 只检查已完成的订单
            if order.status == OrderStatus.COMPLETED:
                for item in order.items:
                    if item.product_id == product_id:
                        return True
        
        return False
    
    def get_product_orders(self, product_id: str) -> List[Order]:
        """
        获取包含指定商品的所有订单
        
        Args:
            product_id: 商品ID
            
        Returns:
            List[Order]: 订单列表
        """
        all_orders = self.get_all_orders()
        product_orders = []
        
        for order in all_orders:
            for item in order.items:
                if item.product_id == product_id:
                    product_orders.append(order)
                    break
        
        return product_orders
    
    @handle_critical_errors("支付订单失败，请重试")
    def pay_order(self, order_id: str) -> bool:
        """
        支付订单（将订单状态从待支付更新为已支付）
        
        Args:
            order_id: 订单ID
            
        Returns:
            bool: 是否支付成功
        """
        order = self.get_order_by_id(order_id)
        
        if not order:
            warning(f"❌ Order {order_id} does not exist")
            return False
        
        if not order.can_pay():
            warning(f"❌ Order {order_id} in status {order.status} cannot be paid")
            return False
        
        # 更新订单状态为已支付
        success = self.update_order_status(order_id, OrderStatus.PAID)
        if success:
            info(f"✅ Order {order_id} paid successfully")
        return success
    
    def ship_order(self, order_id: str) -> bool:
        """
        发货订单（将订单状态从已支付更新为已发货）
        
        Args:
            order_id: 订单ID
            
        Returns:
            bool: 是否发货成功
        """
        order = self.get_order_by_id(order_id)
        
        if not order:
            warning(f"❌ Order {order_id} does not exist")
            return False
        
        if not order.can_ship():
            warning(f"❌ Order {order_id} in status {order.status} cannot be shipped")
            return False
        
        # 更新订单状态为已发货
        success = self.update_order_status(order_id, OrderStatus.SHIPPED)
        if success:
            info(f"✅ Order {order_id} shipped")
        return success
    
    def complete_order(self, order_id: str) -> bool:
        """
        完成订单（将订单状态从已发货更新为已完成）
        
        Args:
            order_id: 订单ID
            
        Returns:
            bool: 是否完成成功
        """
        order = self.get_order_by_id(order_id)
        
        if not order:
            warning(f"❌ Order {order_id} does not exist")
            return False
        
        if not order.can_complete():
            warning(f"❌ Order {order_id} in status {order.status} cannot be completed")
            return False
        
        # 更新订单状态为已完成
        success = self.update_order_status(order_id, OrderStatus.COMPLETED)
        if success:
            info(f"✅ Order {order_id} completed")
        return success
    
    @handle_critical_errors("Failed to delete order, please retry")
    def delete_order(self, order_id: str) -> bool:
        """删除订单（带状态验证）"""
        try:
            # 先检查订单是否存在和是否可以删除
            order = self.get_order_by_id(order_id)
            if not order:
                warning(f"❌ Order {order_id} does not exist")
                return False
            
            if not order.can_delete():
                warning(f"❌ Order {order_id} in status {order.status} cannot be deleted")
                return False
            
            # 注意：删除已取消的订单时，库存已经被恢复了
            # 删除已发货或已完成的订单时，库存不需要再次恢复
            
            orders = self.get_all_orders()
            original_count = len(orders)
            
            # 过滤掉要删除的订单
            orders = [order for order in orders if order.order_id != order_id]
            
            if len(orders) < original_count:
                # 保存更新后的订单列表
                orders_data = [order.to_dict() for order in orders]
                self.data_manager.save_data('orders.json', orders_data)
                info(f"✅ Order {order_id} deleted successfully")
                return True
            else:
                warning(f"❌ Order {order_id} does not exist")
                return False
                
        except Exception as e:
            error(f"❌ Failed to delete order: {e}")
            return False

